<template>
  <div id="DoAnswerPage">
    <a-card>
      <h1>{{ app?.appName }}</h1>
      <p>{{ app?.appDesc }}</p>
      <h2 style="margin-bottom: 32px">
        {{ current }}、{{ currentQuestion?.title }}
      </h2>
      <div>
        <div>
          <a-radio-group
            v-model="currentAnswer"
            :options="questionOptions as any"
            @change="doRadioChange"
          ></a-radio-group>
        </div>
      </div>
      <div style="margin-bottom: 24px">
        <a-space size="large">
          <a-button
            type="primary"
            circle
            v-if="current < questionList.length"
            :disabled="!currentAnswer"
            @click="current += 1"
            >下一题
          </a-button>
          <a-button
            type="primary"
            v-if="current == questionList.length"
            :loading="submitting"
            circle
            :disabled="!currentAnswer"
            @click="handleSubmit"
          >
            {{ submitting ? "评估中" : "查看结果" }}
          </a-button>
          <a-button
            type="primary"
            circle
            v-if="current > 1"
            @click="current -= 1"
            >上一题
          </a-button>
        </a-space>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  defineProps,
  reactive,
  ref,
  watchEffect,
  withDefaults,
} from "vue";
import { useLoginUserStore } from "@/store/userStore";
import meassage from "@arco-design/web-vue/es/message";
import API from "@/api";
import { useRouter } from "vue-router";

import message from "@arco-design/web-vue/es/message";
import {
  addQuestionUsingPost,
  editQuestionUsingPost,
  listQuestionVoByPageUsingPost,
} from "@/api/questionController";
import { getAppVoByIdUsingGet } from "@/api/appController";
import {
  addUserAnswerUsingPost,
  genrateIdUsingGet,
} from "@/api/userAnswerController";

const loginUserStore = useLoginUserStore();
const router = useRouter();
const form = ref({
  appDesc: "",
  appIcon: "",
  appName: "",
  appType: 0,
  scoringStrategy: 0,
} as API.AppAddRequest);

interface Props {
  appId: string;
}

const props = withDefaults(defineProps<Props>(), {
  appId: () => {
    return "";
  },
});

const app = ref<API.AppVO>();
const submitting = ref(false);

//题目结构
const questionList = ref([] as API.QuestionContenDto[]);

//当前的题目（从1开始）
const current = ref(1);

//当前题目
const currentQuestion = ref<API.QuestionContenDto>();

//当前题目选项
const questionOptions = computed(() => {
  return currentQuestion.value?.options
    ? currentQuestion.value.options.map((option) => ({
        label: `${option.key}. ${option.value}`,
        value: option.key,
      }))
    : [];
});

//当前答案

const currentAnswer = ref<string>();
//回答列表
const answerList = reactive<string[]>([]);

const onRadioChange = (value: string) => {
  currentAnswer.value = value;
  // 记录回答
  answerList[current.value - 1] = value;
};
/**
 * 选中选项后，保存答案
 * @param value
 */

const id = ref<number>();
//生成唯一ID
const generateId = async () => {
  const res = await genrateIdUsingGet();
  if (res.data.code === 0) {
    id.value = res.data.data;
  } else {
    message.error("获取唯一ID失败，" + res.data.message);
  }
};
//进入页面时，生成唯一ID
watchEffect(() => {
  generateId();
});

const doRadioChange = (value: string) => {
  answerList[current.value - 1] = value;
};

const loadData = async () => {
  let res: any;
  if (!props.appId) {
    return;
  }
  //获取App
  res = await getAppVoByIdUsingGet({
    id: props.appId as any,
  });
  if (res.data.code === 0) {
    app.value = res.data.data;
  } else {
    message.error("获取数据失败，" + res.data.message);
  }

  //获取题目
  res = await listQuestionVoByPageUsingPost({
    appId: props.appId as any,
    current: 1,
    pageSize: 1,
    sortField: "createTime",
    sortOrder: "descend",
  });
  if (res.data.code === 0 && res.data.data?.records) {
    questionList.value = res.data.data?.records[0].questionContent;
    console.log(questionList.value);
  } else {
    message.error("获取题目失败，" + res.data.message);
  }
};

watchEffect(() => {
  loadData();
});
//改变current题目后，会自动更新当前题目和答案
watchEffect(() => {
  currentQuestion.value = questionList.value[current.value - 1];
  currentAnswer.value = answerList[current.value - 1];
});

/**
 * 提交
 * @param data
 */
const handleSubmit = async () => {
  if (!props.appId || !answerList) {
    return;
  }
  submitting.value = true;

  const res = await addUserAnswerUsingPost({
    appId: props.appId as any,
    choices: answerList,
    id: id.value as any,
  });

  if (res.data.code === 0 && res.data.data) {
    router.push(`/answer/result/${res.data.data}`);
  } else {
    meassage.error("提交答案失败," + res.data.message);
  }
  submitting.value = false;
};
</script>
